package org.yiqixue.accounts.service.impl;

import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.yiqixue.accounts.dto.TransactionDto;
import org.yiqixue.accounts.entity.Accounts;
import org.yiqixue.accounts.entity.Transaction;
import org.yiqixue.accounts.mapper.TransactionMapper;
import org.yiqixue.accounts.repository.AccountsRepository;
import org.yiqixue.accounts.repository.TransactionRepository;
import org.yiqixue.accounts.service.ITransactionService;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

// Transaction 服务层实现类，实现 ITransactionService 接口
@Service
@AllArgsConstructor
public class TransactionService implements ITransactionService {

    private final TransactionRepository transactionRepository;
    private final AccountsRepository accountsRepository;

    // 根据手机号和交易类型查询当日的所有交易记录
    @Override
    public List<TransactionDto> getTransactionsByMobileNumberAndType(String mobileNumber, String type) {
        // 根据手机号查询账户信息
        Optional<Accounts> accountsOptional = accountsRepository.findByCustomerId(getCustomerIdByMobileNumber(mobileNumber));
        if (accountsOptional.isPresent()) {
            Long accountNumber = accountsOptional.get().getAccountNumber();
            // 根据账户 ID、交易类型和交易日期查询交易记录
            List<Transaction> transactions = transactionRepository.findByAccountNumberAndTypeAndTransactionDate(accountNumber, type, LocalDate.now());
            // 将 Transaction 实体列表转换为 TransactionDto 列表
            return transactions.stream()
                    .map(transaction -> TransactionMapper.mapToTransactionDto(transaction, new TransactionDto()))
                    .collect(Collectors.toList());
        }
        return List.of();
    }

    // 插入一条交易记录
    @Override
    public TransactionDto createTransaction(TransactionDto transactionDto) {
        // 将 TransactionDto 转换为 Transaction 实体
        Transaction transaction = TransactionMapper.mapToTransaction(transactionDto, new Transaction());
        // 保存交易记录
        Transaction savedTransaction = transactionRepository.save(transaction);
        // 将保存后的 Transaction 实体转换为 TransactionDto
        return TransactionMapper.mapToTransactionDto(savedTransaction, new TransactionDto());
    }

    // 根据手机号获取客户 ID
    private Long getCustomerIdByMobileNumber(String mobileNumber) {
        // 这里需要实现根据手机号查询客户 ID 的逻辑
        // 假设已经有相应的方法可以实现该功能
        return null;
    }
}